using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Xml.Linq;
using System.Net;

namespace VsxFactory.ExtensionManager {
    public class DataServicePackageRepository : IPackageRepository 
    {
        private readonly DataServiceContext _context;

        public DataServicePackageRepository(Uri serviceRoot) {
            UriBuilder ub = new UriBuilder(serviceRoot);
            ub.Path += "/VsixGallery.svc";
            _context = new DataServiceContext(ub.Uri);
            _context.IgnoreMissingProperties = true;
        }

        public IQueryable<DataServicePackage> GetPackages()
        {
            // REVIEW: Is it ok to assume that the package entity set is called packages?
            return new BatchedDataServiceQuery<DataServicePackage>(_context, "Packages");
        }

        public string Source
        {
            get { return _context.BaseUri.ToString(); }
        }

        public bool CheckRepositoryAccess()
        {
            try
            {
                WebRequest wr = WebRequest.Create(_context.GetMetadataUri());
                wr.GetResponse();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
